package com.lb.shopguide.ui.fragment.guide.goods;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.viewpager.AdapterGoodsType;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.goods.GoodsInListBean;
import com.lb.shopguide.entity.goods.GoodsTypeBean;
import com.lb.shopguide.event.guide.SearchBarcodeSelectgoodsEvent;
import com.lb.shopguide.event.guide.SelectGoodsEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.activity.MessageDetailChooseActivity;
import com.lb.shopguide.ui.activity.ScanSmallActivity;
import com.lb.shopguide.ui.fragment.guide.FragmentSearch;
import com.lb.shopguide.ui.view.NormalEdittextTitleBar;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/6/7.
 */

public class FragmentSelectGoods extends BaseCommonFragment {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.neb)
    NormalEdittextTitleBar neb;
    @BindView(R.id.tabs)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.layout_tab)
    LinearLayout layoutTab;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.tv_send_goods)
    TextView tvSendGoods;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.layout_publish_goods)
    LinearLayout layoutPublishGoods;
    @BindView(R.id.layout_scan)
    LinearLayout layoutScan;
    @BindView(R.id.layout_bottom)
    LinearLayout layoutBottom;

    private AdapterGoodsType mAdapterGoodsType;
    private List<GoodsTypeBean> mGoodsTypeList;

    private int goodsSelectType = -1;

    public static FragmentSelectGoods newInstance(int type) {
        FragmentSelectGoods fragment = new FragmentSelectGoods();
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.GOODS_SELECT_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_goods_management;
    }

    @Override
    public void initData() {
        mGoodsTypeList = new ArrayList<>();
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.GOODS_SELECT_TYPE)) {
            goodsSelectType = bundle.getInt(AppConstant.GOODS_SELECT_TYPE);
        }
        sendRequestGetGoodsType();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        tvEmpty.setText("暂无商品，点击刷新页面");
        bindInfoType();
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setRightImageSrc(R.drawable.iv_red_search);
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }


    @Override
    public String getPageTag() {
        return FragmentSelectGoods.class.getName();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (goodsSelectType != -1) {
            bindInfoType();
        }
    }


    private void bindInfoType() {
        if (goodsSelectType == AppConstant.GOODS_SELECT_IN_CHAT) {
            layoutBottom.setVisibility(View.GONE);
            tvSendGoods.setVisibility(View.VISIBLE);
            ntb.setTitleText("发送商品");
        } else if (goodsSelectType == AppConstant.GOODS_SELECT_IN_MANAGEMENT) {
            layoutBottom.setVisibility(View.VISIBLE);
            tvSendGoods.setVisibility(View.GONE);
            ntb.setTitleText("商品管理");
        } else if (goodsSelectType == AppConstant.GOODS_SELECT_IN_CHECKOUT) {
            ntb.setVisibility(View.GONE);
            neb.setVisibility(View.VISIBLE);
            neb.setLeftImageSrc(R.drawable.iv_back);
            neb.setOnLeftImageListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    leftClick();
                }
            });
        }
    }

    private void addAllType() {
        GoodsTypeBean allType = new GoodsTypeBean();
        allType.setTypeName("全部");
        mGoodsTypeList.add(allType);
    }

    private void bindType() {
        layoutTab.setVisibility(View.VISIBLE);
        layoutEmpty.setVisibility(View.GONE);
        mAdapterGoodsType = new AdapterGoodsType(getChildFragmentManager(), mGoodsTypeList, goodsSelectType);
        mViewPager.setAdapter(mAdapterGoodsType);
        mViewPager.setOffscreenPageLimit(4);
        mTabLayout.setViewPager(mViewPager);
    }

    private void bindEmptyType() {
        layoutTab.setVisibility(View.GONE);
        layoutEmpty.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void sendRequestGetGoodsType() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonGoodsType = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonGoodsType.size() != 0) {
                        addAllType();
                        for (JsonElement obj : jsonGoodsType) {
                            GoodsTypeBean bean = JsonUtil.getGson().fromJson(obj, GoodsTypeBean.class);
                            mGoodsTypeList.add(bean);
                        }
                        bindType();
                    } else {
                        bindEmptyType();
                    }
                }
            }
        };
        ApiMethodGuide.getGoodsTypesByShop(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getStoreCode(), this, FragmentEvent.DESTROY_VIEW);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mEvent != null) {
            getSearchResult(mEvent);
            mEvent = null;
        }
    }

    /**
     * 搜索得到的商品处理
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectGoodsEvent(SelectGoodsEvent event) {
        GoodsInListBean bean = event.getGoodsInListBean();
        if (goodsSelectType == AppConstant.GOODS_SELECT_IN_CHAT) {
            List<GoodsInListBean> list = new ArrayList<>();
            list.add(bean);
            ((MessageDetailChooseActivity) _mActivity).onGoodsSelected(list);
            _mActivity.finish();
        } else if (goodsSelectType == AppConstant.GOODS_SELECT_IN_MANAGEMENT) {
            start(FragmentGoodsDetail.newInstance(bean.getProductCode(), AppConstant.GOODS_DETAIL_NORMAL));
        }
    }

    private SearchBarcodeSelectgoodsEvent mEvent;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSearchBarcode(SearchBarcodeSelectgoodsEvent event) {
        if (isStateSaved()) {
            mEvent = event;
        } else {
            getSearchResult();
        }
    }

    private void getSearchResult() {
        if (mGoodsTypeList != null && mGoodsTypeList.size() != 0) {
            start(FragmentSearch.newInstance(AppConstant.SEARCH_GOODS, goodsSelectType, mGoodsTypeList.get(mViewPager.getCurrentItem()).getTypeCode()));
        } else {
            ToastUtils.showShort("没有任何商品类型");
        }
    }

    private void getSearchResult(SearchBarcodeSelectgoodsEvent event) {
        if (mGoodsTypeList != null && mGoodsTypeList.size() != 0) {
            start(FragmentSearch.newInstance(AppConstant.SEARCH_GOODS, goodsSelectType, mGoodsTypeList.get(mViewPager.getCurrentItem()).getTypeCode(), event.getBarcode()));
        } else {
            ToastUtils.showShort("没有任何商品类型");
        }
    }


    private void startSearch() {
        if (mGoodsTypeList != null && mGoodsTypeList.size() != 0) {
            start(FragmentSearch.newInstance(AppConstant.SEARCH_GOODS, goodsSelectType, mGoodsTypeList.get(mViewPager.getCurrentItem()).getTypeCode()));
        } else {
            ToastUtils.showShort("没有任何商品类型,请先添加商品");
        }
    }

    //    @Override
//    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
//        super.onFragmentResult(requestCode, resultCode, data);
//        if (requestCode == AppConstant.REQUEST_CODE_GET_GOODS && resultCode == RESULT_OK && data != null) {
//            setFragmentResult(data);
//        }
//    }
    @OnClick(R.id.tv_send_goods)
    void sendGoods() {
        List<Fragment> list = getChildFragmentManager().getFragments();
        FragmentGoodsList fragmentGoodsList = (FragmentGoodsList) list.get(mViewPager.getCurrentItem());
        List<GoodsInListBean> resultList = fragmentGoodsList.getSelectedGoodsList();
        if (resultList.size() != 0) {
            ((MessageDetailChooseActivity) _mActivity).onGoodsSelected(resultList);
            _mActivity.finish();
        } else {
            ToastUtils.showShort("请选择商品再发送");
        }
    }

    @OnClick(R.id.image_left)
    void leftClick() {
        if (goodsSelectType == AppConstant.GOODS_SELECT_IN_CHAT) {
            _mActivity.finish();
        } else {
            pop();
        }
    }

    @OnClick(R.id.image_right)
    void rightClick() {
        startSearch();
    }

    @OnClick(R.id.layout_publish_goods)
    void publishGoods() {
        if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
            start(FragmentPublishGoods.newInstance("https://singlepage.storeer.com/v2/editGoods_n?" + "staffCode=" + mUserConfigManager.getUserId()
                    + "&id=0" + "&token=" + mUserConfigManager.getUserToken() + "&type=android", AppConstant.PUBLISH_TYPE_NEW));
        } else {
            start(FragmentPublishGoods.newInstance("http://192.168.1.102:8088/v2/editGoods_n?" + "staffCode=" + mUserConfigManager.getUserId()
                    + "&id=0" + "&token=" + mUserConfigManager.getUserToken() + "&type=android", AppConstant.PUBLISH_TYPE_NEW));
        }
    }

    @OnClick(R.id.layout_scan)
    void scan() {
        Intent intent = new Intent(mContext, ScanSmallActivity.class);
        intent.putExtra(AppConstant.SCAN_MODE, AppConstant.SCAN_RETURN_GOODS);
        intent.putExtra(AppConstant.SCAN_FROM, AppConstant.SCAN_FROM_SELECT_GOODS);
        startActivity(intent);
    }


    @OnClick(R.id.layout_search)
    void search() {
        startSearch();
    }

    @OnClick(R.id.tv_empty)
    void emptyClick() {
        sendRequestGetGoodsType();
    }
}
